package com.xiao.mall.message.domain.converter;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.xiao.mall.message.service.dto.TpnsIosMessage;
import org.springframework.util.StringUtils;

import javax.persistence.AttributeConverter;

public class TpnsIosMessageConverter implements AttributeConverter<TpnsIosMessage, String> {
    private final static ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public String convertToDatabaseColumn(TpnsIosMessage iosMessage) {
        try {
            return objectMapper.writeValueAsString(iosMessage);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    @Override
    public TpnsIosMessage convertToEntityAttribute(String str) {
        if (!StringUtils.hasLength(str)) {
            return null;
        }

        try {
            TpnsIosMessage iosMessage = objectMapper.readValue(str,
                    new TypeReference<TpnsIosMessage>() {});
            return iosMessage;
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }
}
